<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>新增文章</title>
    <link rel="stylesheet" href="/static/pengpai/component/pear/css/pear.css" />
    <link href="/static/pengpai/component/layui/css/layui.css" rel="stylesheet" media="all">
    <link href="/static/pengpai/component/code/css/style.css" rel="stylesheet">

    <link href="/static/pengpai/component/wangeditor/normalize.min.css" rel="stylesheet">
    <link href="/static/pengpai/component/wangeditor/wangeditor5.css" rel="stylesheet">

<!--    <link href="https://cdn.bootcdn.net/ajax/libs/normalize/8.0.1/normalize.min.css" rel="stylesheet">-->
<!--    <link href="https://unpkg.com/@wangeditor/editor@latest/dist/css/style.css" rel="stylesheet">-->
    <style>
        #editor—wrapper {
            border: 1px solid #ccc;
            z-index: 100; /* 按需定义 */
        }
        #editor-toolbar { border-bottom: 1px solid #ccc; }
        #editor-text-area { height: 500px; }
    </style>

</head>
<body>
<form class="layui-form layui-col-xs10 layui-col-md8 layui-col-md-offset2" action="" onsubmit="return false">
    <div class="layui-form-item" style="height: 10px"></div>
    <div class="layui-form-item">
        <label class="layui-form-label">所属栏目:</label>
        <div class="layui-input-block">
            <ul class="dtree" data-id="-1" id="selectParent" name="categoryId"></ul>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">文章名称:</label>
        <div class="layui-input-block">
            <input type="text" name="articleName" required  lay-verify="required" placeholder="请输入输入框内容" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">作   者 :</label>
        <div class="layui-input-block">
            <input type="text" name="author" required  lay-verify="required" placeholder="请输入作者" autocomplete="off" class="layui-input" value="彭派数字">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">是否轮播:</label>
        <div class="layui-input-block">
            <input type="radio" name="isCover" value="1" title="是" >
            <input type="radio" name="isCover" value="0" title="否" checked>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">文   章:</label>
        <div class="layui-input-block">
            <input type="radio" name="isArticle" value="1" title="是" >
            <input type="radio" name="isArticle" value="0" title="否" checked>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">是否发布:</label>
        <div class="layui-input-block">
            <input type="radio" name="isShow" value="1" title="是" >
            <input type="radio" name="isShow" value="0" title="否" checked>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">发布时间:</label>
        <div class="layui-input-block">
            <input type="text" class="layui-input" name="publishTime" id="timeElem" placeholder="yyyy-MM-dd">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">跳转方式:</label>
        <div class="layui-input-block">
            <select name="linkTarget" lay-verify="required" lay-search>
                <option value=""></option>
                <option value="1">当前页（_self）</option>
                <option value="2">新标签页（_blank）</option>
            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">上传图片:</label>
        <div class="layui-input-block">
            <button type="button" class="layui-btn" id="test1">上传图片</button>
            <button type="button" class="layui-btn" id="test2">删除图片</button>
            <div class="layui-upload-list">
                <img class="layui-upload-img" id="demo1" style="height: 150px; width: 150px">
                <p id="demoText"></p>
                <input id="resData" type="hidden" name="coverImage"  placeholder="请输入输入框内容" autocomplete="off" class="layui-input">
            </div>
            <div style="width: 95px;">
                <div class="layui-progress layui-progress-big" lay-showpercent="yes" lay-filter="demo">
                    <div class="layui-progress-bar" lay-percent=""></div>
                </div>
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">上传附件:</label>
        <div class="layui-input-block">
            <button type="button" class="layui-btn layui-btn-normal" id="testList">选择多文件</button>
            <div class="layui-upload-list" style="max-width: 1000px;">
                <table class="layui-table">
                    <colgroup>
                        <col>
                        <col width="150">
                        <col width="260">
                        <col width="150">
                    </colgroup>
                    <thead>
                    <tr><th>文件名</th>
                        <th>大小</th>
                        <th>上传进度</th>
                        <th>操作</th>
                    </tr></thead>
                    <tbody id="demoList"></tbody>
                </table>
            </div>
            <button type="button" class="layui-btn" id="testListAction">开始上传</button>
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">文章介绍:</label>
        <div class="layui-input-block">
            <textarea name="articleDescription" placeholder="请输入内容" class="layui-textarea"></textarea>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">文章内容:</label>
        <div class="layui-input-block">
            <div id="editor-toolbar" class="editor-toolbar"></div>
            <div id="editor-text-area" name="content" class="editor-text-area"></div>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">显示顺序:</label>
        <div class="layui-input-block">
            <input type="text" name="sort" placeholder="请输入输入框内容" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="articleAdd">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>

<!--<script src="https://unpkg.com/@wangeditor/editor@latest/dist/index.js"></script>-->
<!--<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>-->

<script src="/static/pengpai/component/wangeditor/wangeditor5.js"></script>
<script src="/static/pengpai/admin/js/jquery.min.js"></script>

<script src="/static/pengpai/component/layui/layui.js"></script>
<script src="/static/pengpai/component/pear/pear.js"></script>
<script>
    layui.use(['form', 'jquery', 'dtree', 'popup', 'layer', 'laydate', 'table'], function() {
        let form = layui.form;
        let $ = layui.jquery;
        let dtree = layui.dtree;
        let popup = layui.popup;
        var upload = layui.upload;
        var element = layui.element;
        const E = window.wangEditor;
        var laydate = layui.laydate;

        laydate.render({
            elem: '#timeElem', //指定元素
            type: 'date',
        });

        dtree.renderSelect({
            elem: "#selectParent",
            url: "/webCategory/selectParent",
            method: 'get',
            selectInputName: {nodeId: "categoryId", context: "categoryName"},
            skin: "layui",
            dataFormat: "list",
            response: {treeId: "categoryId", parentId: "parentId", title: "categoryName"},  //修改response中返回数据的定义
            selectInitVal: "0"
        });

        //常规使用 - 普通图片上传
        var uploadInst = upload.render({
            elem: '#test1',
            url: '/sysFileinfo/upload', //此处用的是第三方的 http 请求演示，实际使用时改成您自己的上传接口即可。
            before: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    $('#demo1').attr('src', result); //图片链接（base64）
                });

                element.progress('demo', '0%'); //进度条复位
                layer.msg('上传中', {icon: 16, time: 0});
            },
            done: function(res){
                //如果上传失败
                if(res.code == 500){
                    return layer.msg('上传失败');
                }
                //上传成功的一些操作
                //……
                $('#demoText').html(''); //置空上传失败的状态
                // var demoText = $('#demoText');
                // demoText.html('<input type="text" name="imagePath" th:value="#{res.code}" placeholder="请输入输入框内容" autocomplete="off" class="layui-input">');
                const resData = document.getElementById('resData');
                resData.value = res.data
            },
            error: function(){
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function(){
                    uploadInst.upload();
                });
            },
            //进度条
            progress: function(n, elem, e){
                element.progress('demo', n + '%'); //可配合 layui 进度条元素使用
                if(n == 100){
                    layer.msg('上传完毕', {icon: 1});
                }
            }
        });
        let fileIds = "";
        //演示多文件列表
        var uploadListIns = upload.render({
            elem: '#testList'
            ,elemList: $('#demoList') //列表元素对象
            ,url: '/sysFileinfo/upload' //此处用的是第三方的 http 请求演示，实际使用时改成您自己的上传接口即可。
            ,accept: 'file'
            ,exts: 'zip|rar|7z|jpg|png|gif|bmp|jpeg|doc|docs|pdf|xlsx|xls|ppt|pptx|svg'
            ,multiple: true
            ,number: 5
            ,auto: false
            ,bindAction: '#testListAction'
            ,choose: function(obj){
                var that = this;
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //读取本地文件
                console.log("..." + obj)
                obj.preview(function(index, file, result){

                    var tr = $(['<tr id="upload-'+ index +'">'
                        ,'<td>'+ file.name +'</td>'
                        ,'<td>'+ (file.size/1024).toFixed(1) +'kb</td>'
                        ,'<td><div class="layui-progress" lay-filter="progress-demo-'+ index +'"><div class="layui-progress-bar" lay-percent=""></div></div></td>'
                        ,'<td>'
                        ,'<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        ,'<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        ,'</td>'
                        ,'</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function(){
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function(){
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                    });

                    that.elemList.append(tr);
                    element.render('progress'); //渲染新加的进度条组件
                });
            }
            ,done: function(res, index, upload){ //成功的回调
                var that = this;
                //if(res.code == 0){ //上传成功
                var tr = that.elemList.find('tr#upload-'+ index)
                    ,tds = tr.children();
                // tds.eq(3).html(''); //清空操作
                fileIds = fileIds + res.data + ",";

                delete this.files[index]; //删除文件队列已经上传成功的文件
                return;
                //}
                this.error(index, upload);
            }
            ,allDone: function(obj){ //多文件上传完毕后的状态回调
                console.log(obj)
            }
            ,error: function(index, upload){ //错误回调
                var that = this;
                var tr = that.elemList.find('tr#upload-'+ index)
                    ,tds = tr.children();
                tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
            }
            ,progress: function(n, elem, e, index){ //注意：index 参数为 layui 2.6.6 新增
                element.progress('progress-demo-'+ index, n + '%'); //执行进度条。n 即为返回的进度百分比
            }
        });

        // Change language
        const LANG = location.href.indexOf('lang=en') > 0 ? 'en' : 'zh-CN'
        E.i18nChangeLanguage(LANG)

        const editorConfig = { MENU_CONF: {} }
        editorConfig.MENU_CONF['uploadImage'] = {
            server: '/sysFileinfo/wangEditUpload',
            // server: '/api/upload-img-10s', // test timeout
            // server: '/api/upload-img-failed', // test failed
            // server: '/api/xxx', // test 404

            timeout: 50 * 1000, // 5s

            fieldName: 'file',
            // meta: { token: 'xxx', a: 100 },
            metaWithUrl: true, // join params to url
            // headers: { Accept: 'text/x-json' },
            headers: { Accept: 'text/application' },

            maxFileSize: 10 * 1024 * 1024, // 10M

            base64LimitSize: 5 * 1024, // insert base64 format, if file's size less than 5kb

            onBeforeUpload(file) {
                console.log('onBeforeUpload', file)

                return file // will upload this file
                // return false // prevent upload
            },
            onProgress(progress) {
                console.log('onProgress', progress)
            },
            onSuccess(file, res) {
                console.log('onSuccess', file, res)
            },
            onFailed(file, res) {
                alert(res.message)
                console.log('onFailed', file, res)
            },
            onError(file, err, res) {
                alert(err.message)
                console.error('onError', file, err, res)
            },
        }

        editorConfig.MENU_CONF['uploadVideo'] = {
            server: '/sysFileinfo/wangEditUpload',
            // server: '/api/upload-img-failed', // test failed
            // server: '/api/xxx', // test 404

            timeout: 50 * 1000, // 50s

            fieldName: 'file',
            // meta: { token: 'xxx', a: 100 },
            metaWithUrl: true, // join params to url
            headers: { Accept: 'text/x-json' },
            // headers: { Accept: 'text/application' },

            maxFileSize: 50 * 1024 * 1024, // 50M

            onBeforeUpload(file) {
                console.log('onBeforeUpload', file)

                return file // will upload this file
                // return false // prevent upload
            },
            onProgress(progress) {
                console.log('onProgress', progress)
            },
            onSuccess(file, res) {
                console.log('onSuccess', file, res)
            },
            onFailed(file, res) {
                alert(res.message)
                console.log('onFailed', file, res)
            },
            onError(file, err, res) {
                alert(err.message)
                console.error('onError', file, err, res)
            },
        }

        const editor = E.createEditor({
            selector: '#editor-text-area',
            // html: '<p>此处输入文章</p><p><br></p>',
            config: editorConfig
        })

        const toolbar = E.createToolbar({
            editor,
            selector: '#editor-toolbar',
            // config: {}
        })

        var clearBtn = document.getElementById("test2");
        clearBtn.addEventListener("click", function () {
            layer.confirm('确定要删除该图片', {
                title: '提示'
            }, function(index) {
            layer.close(index);
            let loading = layer.load();
            $('#demo1').attr('src', null);
            // uploadInst.progress('demo', '0%');
            var uuid = document.getElementById("resData").value;
            document.getElementById("resData").value=null;
            // debugger
            $.ajax({
                url: "/sysFileinfo/delete",
                dataType: 'json',
                type: 'post',
                data: {"uuid":uuid},
                success: function(result) {
                    layer.close(loading);
                    if (result.code == 200) {
                        layer.msg(result.msg, function() {
                                // obj.del();
                        });
                    } else {
                        popup.failure(result.msg);
                    }
                }
                })
            });
        });

        form.on('submit(articleAdd)', function(data) {
            data.field.fileCodes = fileIds;
            data.field.content  = editor.getText
            data.field.htmlContent  = editor.getHtml

            $.post("/webArticle/create",data.field,function(r){
                console.info(r.code);
                if(r.code === 200){
                    popup.success(r.msg, function () {
                        // console.log(obj);
                        var iframeIndex = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(iframeIndex);
                        parent.location.reload();
                    });
                }else{
                    popup.failure(r.msg);
                }
            });
        });

    })
</script>
<script>
</script>
</body>
</html>
